from hashlib import md5
from time import time
from urllib import url2pathname


APP_ID = 162859177101861
APP_SECRET = "8cb9080fef1d14dddfdde0ed78570453"
NOT_CORRECT_ID = 'NaN'


class FbCookieError(Exception):
    pass


def get_fb_user_id(fb_user_cookie):
    """Checks authorization"""
    fb_user_cookie = url2pathname(fb_user_cookie)
    data_array = {}
    fb_data = fb_user_cookie.split('&')
    valid_keys = ('expires', 'uid', 'secret', 'sig')   
    try:    
        # parse cookie
        for fb_data_param in fb_data:
            key, value = fb_data_param.split('=')
            if not key or not value:
                raise FbCookieError('1')
            data_array[key] = value
        for key in valid_keys:
            if not data_array[key]:
                raise FbCookieError('2')
        
        # create string for md5
        strings = []
        for key in sorted(data_array.keys()):
            if key != 'sig':
                strings.append('{0}={1}'.format(key, data_array[key]))
        strings.append(APP_SECRET)
        sig_md5 = md5(''.join(strings)).hexdigest()

        expires = float(data_array["expires"])
        if data_array['sig'] != sig_md5 or (expires != 0 and time() > expires):
            raise FbCookieError('3')
    except FbCookieError:
        user_id = NOT_CORRECT_ID
    else:
        user_id = data_array['uid']
    return user_id